//
//  SinaTabBar.swift
//  SinaWeiBo
//
//  Created by 王忠楠 on 16/9/19.
//  Copyright © 2016年 wangzn. All rights reserved.
//

import UIKit

//定义代理协议
protocol SinaTabBarDelegate: NSObjectProtocol{
    func didSelectedComposeButton()

}

class SinaTabBar: UITabBar {

    //点击按钮执行的闭包
    
    var composeButtonClosure : (()->())?
    
    weak var sinaDelegate: SinaTabBarDelegate?
    
    //懒加载
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        //添加点击事件
     //   button.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
        
        //设置图片
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        
        //设置大小
        button.sizeToFit()
        
        return button
        
    }()
    
    override init(frame:CGRect){
        super.init(frame: frame)
        setupUI()
    }
    
    
    required init?(coder aDecoder:NSCoder){
        super.init(coder: aDecoder)
        setupUI()
        
    }
    
    //添加控件的函数
    private func setupUI(){
        
        backgroundImage = UIImage(named: "tabbar_background")
        
        
        //添加子视图控件
        addSubview(composeButton)
    }
    
    @objc private func composeButtonAction(){
        
        print("hhh")
        
        
        composeButtonClosure?()
        
        
        sinaDelegate?.didSelectedComposeButton()
        
        
    }
    
    //设置子控件位置
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置按钮中心点
        composeButton.centerX = width / 2
        composeButton.centerY = height / 2
        
        //计算每项按钮的宽度
        let itemWidth = width / 5
        
        //记录遍历到的是第几个系统按钮的索引
        var index = 0
        
        //获取系统按钮的控件
        for value in subviews{
            
            if value.isKind(of: NSClassFromString("UITabBarButton")!)
            {
                
                value.width = itemWidth
                
                value.x = CGFloat(index) * itemWidth
                
                index += 1
                
                if index == 2 {
                    index += 1
                }
            }
            
        }
        
        
        
        
    }

}
